package com.example.enews.fragments

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.enews.R
import com.example.enews.adapters.MatchAdapter
import com.example.enews.models.MatchItem
import com.example.enews.utils.NtpTimeHelper
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Locale
import java.util.concurrent.TimeUnit
import kotlin.math.abs

// MatchFragment.kt
class MatchFragment : Fragment() {
    private lateinit var adapter: MatchAdapter
    private val matchList by lazy { generateSampleData() }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val view = inflater.inflate(R.layout.fragment_match, container, false)
        setupRecyclerView(view)
        fetchMatchData()
        return view
    }

    private fun setupRecyclerView(view: View) {
        val recyclerView = view.findViewById<RecyclerView>(R.id.match_recycler)
        recyclerView.layoutManager = LinearLayoutManager(requireContext())
        adapter = MatchAdapter(matchList)
        recyclerView.adapter = adapter
    }

    private fun generateSampleData(): List<MatchItem> {
        return listOf(
            MatchItem("1", "LPL夏季赛", "02:00", "EDG", "RNG", "BO3", true),
            MatchItem("2", "LCK春季赛", "04:00", "T1", "Gen.G", "BO5", true),
            MatchItem("3", "奥斯汀Major2025", "06:00", "Legacy", "LVG", "BO3", false),
            MatchItem("4", "奥斯汀Major2025", "13:00", "3DMAX", "paiN", "BO3", false),
            MatchItem("5", "奥斯汀Major2025", "01:30", "MongolZ", "FaZe", "BO3", false),
            MatchItem("6", "奥斯汀Major2025", "02:54", "Aurora", "MOUZ", "BO3", false),
            MatchItem("7", "奥斯汀Major2025", "03:53", "VP", "Vitality", "BO3", false),
            MatchItem("8", "奥斯汀Major2025", "04:00", "NAVI", "G2", "BO3", false),
            MatchItem("9", "奥斯汀Major2025", "16:00", "Liquid", "LVG", "BO3", false),
            MatchItem("10", "LCK春季赛", "19:00", "T1", "Gen.G", "BO5", false),
            MatchItem("11", "MSI预选赛", "20:30", "BLG", "WBG", "BO1", false)
        )
    }
    // 修改updateMatchStatus方法中的时间处理
    private suspend fun updateMatchStatus(matches: List<MatchItem>): List<MatchItem> {
        val currentTime = NtpTimeHelper.getNetworkTime()

        return matches.map { match ->
            val sdf = SimpleDateFormat("HH:mm", Locale.getDefault())
            val matchTime = sdf.parse(match.matchTime)?.time ?: return@map match

            // 提取小时和分钟
            val hour = (matchTime / (60 * 60 * 1000)) % 24
            val minute = (matchTime / (60 * 1000)) % 60

            // 设置到当前时间基础上的具体时间
            val matchCalendar = Calendar.getInstance().apply {
                timeInMillis = currentTime
                set(Calendar.HOUR_OF_DAY, hour.toInt())
                set(Calendar.MINUTE, minute.toInt())
                set(Calendar.SECOND, 0)
                set(Calendar.MILLISECOND, 0)
            }

            var matchDateTime = matchCalendar.timeInMillis

            // 如果比赛时间已经过去，则加一天
            if (matchDateTime < currentTime) {
                matchCalendar.add(Calendar.DAY_OF_MONTH, 1)
                matchDateTime = matchCalendar.timeInMillis
            }

            val timeDifference = currentTime - matchDateTime

            val isLive = when {
                timeDifference < 0 -> false // 当前时间早于比赛时间
                timeDifference < TimeUnit.MINUTES.toMillis(5) -> true // 在5分钟内开始的比赛视为“进行中”
                else -> false
            }

            val newIsCompleted = timeDifference >= TimeUnit.MINUTES.toMillis(5)

            match.copy(isLive = isLive, isCompleted = newIsCompleted)
        }
    }


    private fun fetchMatchData() {
        // 使用lifecycleScope启动协程
        lifecycleScope.launch {
            try {
                // 1. 获取原始数据
                val rawMatches = generateSampleData()

                // 2. 异步更新比赛状态
                val matchesWithStatus = updateMatchStatus(rawMatches)

                // 3. 更新UI
                adapter.submitList(matchesWithStatus)
            } catch (e: Exception) {
                // 4. 错误处理（可添加重试机制）
                Log.e("MatchFragment", "Error fetching match data", e)
            }
        }
    }
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        startPeriodicUpdate()
    }

    private var refreshJob: Job? = null

    private fun startPeriodicUpdate() {
        refreshJob?.cancel() // 防止重复启动
        refreshJob = lifecycleScope.launch {
            while (true) {
                delay(TimeUnit.MINUTES.toMillis(1)) // 每分钟刷新一次
                fetchMatchData()
            }
        }
    }
    override fun onDestroyView() {
        super.onDestroyView()
        refreshJob?.cancel()
    }
}
